package jee.boot.module.authority.service;


import com.google.common.collect.Lists;
import jee.boot.common.basic.TreeService;
import jee.boot.entity.auth.Account;
import jee.boot.common.standard.AccountHandler;
import jee.boot.common.standard.AuthorityHandler;
import jee.boot.common.utils.StringUtils;
import jee.boot.module.authority.dao.ResourceDao;
import jee.boot.entity.auth.Resource;
import jee.boot.entity.auth.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 资源
 */
@Service
public class ResourceService extends TreeService<ResourceDao, Resource> {
    @Autowired
    private AccountHandler accountHandler;
    @Autowired
    private UserService userService;
    @Override
    public Resource get(Resource entity) {
        return super.get(entity);
    }

    @Caching(evict = {
            @CacheEvict(value = AuthorityHandler.USER_AUTHORITY_KEY, allEntries = true)
    })
    @Override
    public void update(Resource entity) {
        //更新数据
        super.update(entity);

    }

    @Caching(evict = {
            @CacheEvict(value = AuthorityHandler.USER_AUTHORITY_KEY, allEntries = true)
    })
    @Override
    public void delete(Resource entity) {
        // 删除 资源
        super.delete(entity);

    }


    /**
     * 当前用户的菜单树
     * @return
     */
    public List<Resource> sessionTree() {
        List<Resource> resources = sessionList();
        if(resources!=null && !resources.isEmpty()){
            List<Resource> menuList = resources.stream().filter(r -> StringUtils.equals(r.getType(), "menu")).collect(Collectors.toList());
            return buildTree(menuList);
        }
        return Lists.newArrayList();
    }

    /**
     * 当前用户所有资源
     * @return
     */
    public List<Resource> sessionList() {
        if(accountHandler.isSuperAdministrator()){
            return findList(new Resource());
        }else{
            Account account=accountHandler.getPrincipal();
            User authorization = userService.authorization(new User(account));
            return authorization.getResourceSet().stream().collect(Collectors.toList());
        }
    }

    public List<Resource> newFindList(Resource entity) {
        entity.preQuery();
        List<Resource> list = dao.newFindList(entity);
        entity.postUpdate(list);
        return list;
    }

    public List<Resource> publishList(Resource entity) {
        return dao.publishList(entity);
    }

}